<?php

class SubscribesController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/main';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

  public function actions(){
    return array(
        'captcha'=>array(
            'class'=>'CaptchaExtendedAction',
        ),
    );
  }

	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view', 'create', 'captcha'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	public function actionCreate()
	{
		$model=new Subscribes;

		if(isset($_POST['Subscribes']))
		{
      $check = Users::model()->find('email = :email', array(':email' => $_POST['Subscribes']['email']));

      if(!$check)
      {
        $model->attributes=$_POST['Subscribes'];
        if($model->save())
        {
          Yii::app()->user->setFlash('success', 'Success');
          Yii::app()->user->setFlash('content', 'You have successfully subscribe to our newsletter.');

          $this->redirect(bu("site/news"));
        }
        else
        {
          $errors = $model->getErrors();
          $content = '';

          foreach($errors as $error ){
            $content = $content.$error[0].'<br />';
          }

          Yii::app()->user->setFlash('error', 'Error');
          Yii::app()->user->setFlash('content', $content);

          $this->redirect(bu("site/news"));
        }
      }
      else
      {
        Yii::app()->user->setFlash('error', 'Error');
        Yii::app()->user->setFlash('content', 'Email address already exist in database!');

        $this->redirect(bu("site/news"));
      }
		}
	}

	public function loadModel($id)
	{
		$model=Subscribes::model()->findByPk((int)$id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='subscribes-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
